import { useState, useCallback } from 'react'

interface WasmModule {
  merge_files: (fileBuffers: Uint8Array[]) => string
}

export const useWasm = () => {
  const [wasmModule, setWasmModule] = useState<WasmModule | null>(null)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [loadingPromise, setLoadingPromise] =
    useState<Promise<WasmModule> | null>(null)

  const loadWasm = useCallback(async () => {
    if (wasmModule) return wasmModule // 已经加载过了

    // 如果正在加载中，返回同一个 Promise，避免重复加载
    if (loadingPromise) {
      return loadingPromise
    }

    setIsLoading(true)
    setError(null)

    const promise = (async () => {
      try {
        // 使用动态导入，只有在真正需要时才加载
        const wasmModulePromise = import('@/lib/pkg/example_wasm')
        const { default: init, merge_files } = await wasmModulePromise
        await init()
        const module = { merge_files }
        setWasmModule(module)
        setLoadingPromise(null) // 清除加载 Promise
        return module
      } catch (err) {
        const errorMessage =
          err instanceof Error ? err.message : 'Failed to load WASM module'
        setError(errorMessage)
        setLoadingPromise(null) // 清除加载 Promise
        console.error('Failed to load WASM module:', err)
        throw err
      } finally {
        setIsLoading(false)
      }
    })()

    setLoadingPromise(promise)
    return promise
  }, [wasmModule, loadingPromise])

  // 提供一个预检查方法，避免立即加载
  const isWasmAvailable = useCallback(() => {
    return wasmModule !== null
  }, [wasmModule])

  return {
    wasmModule,
    isLoading,
    error,
    loadWasm,
    isWasmAvailable,
    isLoadingInProgress: !!loadingPromise
  }
}
